package com.example.wly.application_3_homework;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends AppCompatActivity{
    HashMap<String, String> phoneMap = new HashMap<>();
    EditText etNum;
    Button btnCall;
    Button btnAddNum;
    EditText etnNewNum;
    EditText etNewCutNumber;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etNum = (EditText) findViewById(R.id.et_num);
        etnNewNum = (EditText) findViewById(R.id.et_newnum);
        etNewCutNumber = (EditText) findViewById(R.id.et_newcutnumber);
        btnCall = (Button) findViewById(R.id.btn_call);
        btnAddNum = (Button) findViewById(R.id.btn_addnum);

        requestMyappPermission();
        initMapData();

        btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(intent.ACTION_CALL);//拨号
                String cutNumber = etNum.getText().toString().trim();
                String phoneNumber = phoneMap.get(cutNumber);
                intent.setData(Uri.parse("tel:" + phoneNumber));
                startActivity(intent);
            }
        });
        btnAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = etNewCutNumber.getText().toString();
                String value = etnNewNum.getText().toString();
                phoneMap.put(key,value);
                Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                etNewCutNumber.setText("");
                etnNewNum.setText("");
            }
        });
    }

    private void requestMyappPermission() {
        String[] perms = {Manifest.permission.CALL_PHONE};
        if (!EasyPermissions.hasPermissions(getApplicationContext(), perms)) {
            EasyPermissions.requestPermissions(this,"call phone",1,perms);
        }
    }

    private void initMapData() {
        phoneMap.put("1", "10086");
        phoneMap.put("2", "10010");
    }

}
